package com.example.authclient.handler;

import com.taocares.security.core.JsonResponseWrapper;
import com.taocares.security.core.authentication.handler.AbstractJsonAuthenticationFailureHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Description goes here
 *
 * @author ankang
 * @since 2019/5/23
 */
@Component("oauth2AuthenticationFailureHandler")
public class OAuth2AuthenticationFailureHandler extends AbstractJsonAuthenticationFailureHandler {
    @Override
    protected Exception extractException(AuthenticationException e) throws Exception {
        Throwable throwable = e.getCause();
        if (throwable instanceof OAuth2Exception) {
//            // 客户端认证异常需要抛出到框架进行进一步处理
//            if (throwable instanceof ClientAuthenticationException) {
//                throw (ClientAuthenticationException) throwable;
//            }
            return (OAuth2Exception) throwable;
        }
        return null;
    }

    @Override
    protected Map<Class<? extends Exception>, JsonResponseWrapper> defaultMapping() {
        Map<Class<? extends Exception>, JsonResponseWrapper> map = new HashMap<>();

        map.put(UserDeniedAuthorizationException.class, new JsonResponseWrapper(400, 400, "用户拒绝了授权"));
        map.put(InvalidScopeException.class, new JsonResponseWrapper(400, 400, "请求的Scope不合法"));
        map.put(InvalidTokenException.class, new JsonResponseWrapper(400, 400, "请求的Token不合法"));

        return map;
    }

    @Override
    protected int httpStatusCode() {
        return HttpServletResponse.SC_BAD_REQUEST;
    }
}
